<template>
  <!-- 顶部占位 -->
  <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }"></view>
  <view class="container" :style="{ backgroundImage: `url(${counterStore.bg_img})` }">
    <view class="skill-tree">
      <!-- 顶部标题 -->
      <view class="title-box">
        <text class="main-title">神秘塔罗</text>
      </view>

      <!-- 流式布局 -->
      <view class="flex-row">
        <view class="category-title">今日运势（综合AI）</view>
        <view class="skill-item" @tap="showCardSelector">自助解牌</view>
        <view class="skill-item" @tap="showRandomCard">自助抽牌</view>
        <!-- 常用排阵区域 -->
        <template v-if="favoriteLayouts.length > 0">
          <view class="category-title">收藏</view>
          <view class="favorite-layouts">
            <view v-for="layout in favoriteLayouts" :key="layout" class="skill-item-wrapper">
              <view class="skill-item" @tap="navigateToLayout(layout)">{{ layout }}</view>
              <view class="heart-icon active" @tap="toggleFavorite(layout, $event)">❤</view>
            </view>
          </view>
        </template>
        <view class="category-title">选择排阵</view>
        <view class="skill-item-wrapper">
          <view class="skill-item" @tap="navigateToLovePyramid">恋人金字塔</view>
          <view class="heart-icon" :class="{ active: isFavorite('恋人金字塔') }" @tap="toggleFavorite('恋人金字塔', $event)">❤
          </view>
        </view>
        <view class="skill-item-wrapper">
          <view class="skill-item" @tap="navigateToMindBodySpirit">身心灵</view>
          <view class="heart-icon" :class="{ active: isFavorite('身心灵') }" @tap="toggleFavorite('身心灵', $event)">❤</view>
        </view>
        <view class="skill-item-wrapper" v-show="!isFavorite('事业金字塔')">
          <view class="skill-item" @tap="navigateToCareerPyramid">事业金字塔</view>
          <view class="heart-icon" :class="{ active: isFavorite('事业金字塔') }" @tap="toggleFavorite('事业金字塔', $event)">❤
          </view>
        </view>

        <view class="skill-item-wrapper" v-show="!isFavorite('时间之箭')">
          <view class="skill-item" @tap="navigateToTimeArrow">时间之箭</view>
          <view class="heart-icon" :class="{ active: isFavorite('时间之箭') }" @tap="toggleFavorite('时间之箭', $event)">❤
          </view>
        </view>

        <view class="skill-item-wrapper" v-show="!isFavorite('暗恋告白')">
          <view class="skill-item" @tap="navigateToSecretCrush">暗恋告白</view>
          <view class="heart-icon" :class="{ active: isFavorite('暗恋告白') }" @tap="toggleFavorite('暗恋告白', $event)">❤
          </view>
        </view>

        <view class="skill-item-wrapper" v-show="!isFavorite('月运势')">
          <view class="skill-item" @tap="navigateToMonthlyFortune">月运势</view>
          <view class="heart-icon" :class="{ active: isFavorite('月运势') }" @tap="toggleFavorite('月运势', $event)">❤</view>
        </view>

        <view class="skill-item-wrapper" v-show="!isFavorite('桃花运')">
          <view class="skill-item" @tap="navigateToLoveFortune">桃花运</view>
          <view class="heart-icon" :class="{ active: isFavorite('桃花运') }" @tap="toggleFavorite('桃花运', $event)">❤</view>
        </view>

        <view class="skill-item-wrapper" v-show="!isFavorite('梦境解读')">
          <view class="skill-item" @tap="navigateToDreamReading">梦境解读</view>
          <view class="heart-icon" :class="{ active: isFavorite('梦境解读') }" @tap="toggleFavorite('梦境解读', $event)">❤
          </view>
        </view>

        <view class="skill-item-wrapper" v-show="!isFavorite('马蹄铁')">
          <view class="skill-item" @tap="navigateToHorseshoe">马蹄铁</view>
          <view class="heart-icon" :class="{ active: isFavorite('马蹄铁') }" @tap="toggleFavorite('马蹄铁', $event)">❤</view>
        </view>

        <view class="skill-item-wrapper" v-show="!isFavorite('灵感对应')">
          <view class="skill-item" @tap="navigateToInspiration">灵感对应</view>
          <view class="heart-icon" :class="{ active: isFavorite('灵感对应') }" @tap="toggleFavorite('灵感对应', $event)">❤
          </view>
        </view>

        <view class="skill-item-wrapper" v-show="!isFavorite('六芒星')">
          <view class="skill-item" @tap="navigateToHexagram">六芒星</view>
          <view class="heart-icon" :class="{ active: isFavorite('六芒星') }" @tap="toggleFavorite('六芒星', $event)">❤</view>
        </view>

        <view class="skill-item-wrapper" v-show="!isFavorite('统治女神')">
          <view class="skill-item" @tap="navigateToGoddess">统治女神</view>
          <view class="heart-icon" :class="{ active: isFavorite('统治女神') }" @tap="toggleFavorite('统治女神', $event)">❤
          </view>
        </view>

        <view class="skill-item-wrapper" v-show="!isFavorite('心之阴影')">
          <view class="skill-item" @tap="navigateToShadow">心之阴影</view>
          <view class="heart-icon" :class="{ active: isFavorite('心之阴影') }" @tap="toggleFavorite('心之阴影', $event)">❤
          </view>
        </view>
      </view>
    </view>
  </view>

  <!-- 选择牌数弹窗 -->
  <view class="popup" v-if="showPopup" @tap="closePopup">
    <view class="popup-content" @tap.stop>
      <view class="popup-header">
        <text class="popup-title">选择牌数</text>
        <text class="popup-close" @tap="closePopup">取消</text>
        <text class="popup-confirm" @tap="confirmSelection">确认</text>
      </view>
      <view class="card-overflow">
        <view class="card-options">
          <view v-for="(option, index) in cardOptions" :key="index" class="card-option"
            :class="{ active: selectedOption === option }" @tap="selectOption(option)">
            {{ option }}
          </view>
        </view>
      </view>
    </view>
  </view>

  <!-- 随机抽牌弹窗 -->
  <view class="random-popup" v-if="showRandomPopup" @tap="closeRandomPopup">
    <view class="random-content" @tap.stop>
      <!-- 弹窗标题 -->
      <view class="popup-header">
        <text class="popup-title">今日运势</text>
        <text class="popup-close" @tap="closeRandomPopup">×</text>
      </view>
      <!-- 卡片展示区域 -->
      <view class="random-card">
        <image 
          :src="randomCardImage" 
          :class="{ 'card-reverse': isReverse, 'card-drawing': isDrawing }" 
          mode="aspectFit"
          class="card-image" 
        />
      </view>
      <!-- 卡片信息 -->
      <view class="card-info">
        <text class="card-position">{{ isReverse ? '逆位' : '正位' }}</text>
      </view>
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <view class="action-btn" @tap="reDrawCard">重新抽牌</view>
        <view class="action-btn primary" @tap="showCardDetail">查看解读</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useCounterStore } from '@/store/counter';
import { onLoad } from '@dcloudio/uni-app';
const counterStore = useCounterStore();

// 修改收藏相关的状态和方法
const favoriteLayouts = ref<string[]>([])

// 从本地存储加载收藏数据
const loadFavorites = () => {
  try {
    const favorites = uni.getStorageSync('favoriteLayouts')
    if (favorites) {
      favoriteLayouts.value = JSON.parse(favorites)
    }
  } catch (e) {
    console.error('加载收藏数据失败:', e)
  }
}

// 保存收藏数据到本地存储
const saveFavorites = () => {
  try {
    uni.setStorageSync('favoriteLayouts', JSON.stringify(favoriteLayouts.value))
  } catch (e) {
    console.error('保存收藏数据失败:', e)
  }
}

// 修改切换收藏状态的方法
const toggleFavorite = (layoutName: string, event: Event) => {
  event.stopPropagation()
  const index = favoriteLayouts.value.indexOf(layoutName)
  if (index === -1) {
    favoriteLayouts.value.push(layoutName)
  } else {
    favoriteLayouts.value.splice(index, 1)
  }
  // 每次修改后保存到本地存储
  saveFavorites()
}

// 在页面加载时读取收藏数据
onLoad((options) => {
  // 先检查登录状态
  const userInfo = uni.getStorageSync('userInfo') 
  if (!userInfo) {
    uni.navigateTo({ 
      url: "/pages/Login/Login",
      fail: (err) => {
        console.error('跳转登录页面失败:', err)
        uni.showToast({
          title: '跳转失败',
          icon: 'none'
        })
      }
    });
    return; // 如果未登录，直接返回，不执行后续代码
  }

  // 已登录，继续执行其他初始化
  loadFavorites()
  try {
    if (options.cards) {
      receivedCards.value = JSON.parse(decodeURIComponent(options.cards));
    }
  } catch (error) {
    console.error('解码卡牌数据失败:', error);
  }
})

// 检查是否已收藏
const isFavorite = (layoutName: string) => {
  return favoriteLayouts.value.includes(layoutName)
}

// 添加抽牌动画状态
const isDrawing = ref(false)

// 修改抽取随机卡牌方法
const drawRandomCard = () => {
  isDrawing.value = true

  // 添加延时，等待动画完成后再显示结果
  setTimeout(() => {
    // 随机选择一张卡片（0-77）
    const randomIndex = Math.floor(Math.random() * 78)
    // 随机决定正逆位
    isReverse.value = Math.random() > 0.5
    // 设置卡片图片
    randomCardImage.value = `/static/imgs/${randomIndex}.jpg`

    // 动画结束后重置状态
    setTimeout(() => {
      isDrawing.value = false
    }, 500)
  }, 1000)
}
// 定义卡牌数据的类型
interface CardData {
  image: string
  name: string
  position: 'up' | 'down'
}

// 用于接收传递过来的卡牌数据
const receivedCards = ref<CardData[]>([]);

onLoad((options) => {
  try {
    if (options.cards) {
      receivedCards.value = JSON.parse(decodeURIComponent(options.cards));
    }
  } catch (error) {
    console.error('解码卡牌数据失败:', error);
  }

});


// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 弹窗控制
const showPopup = ref(false)
const selectedOption = ref('')

// 牌数选项
const cardOptions = [
  '一张牌',
  '两张牌',
  '三张牌',
  '四张牌',
  '五张牌',
  '六张牌',
  '七张牌'
]

// 随机抽牌相关
const showRandomPopup = ref(false)
const randomCardImage = ref('')
const isReverse = ref(false)

// 显示选择器
const showCardSelector = () => {
  showPopup.value = true
}

// 关闭选择器
const closePopup = () => {
  showPopup.value = false
  selectedOption.value = ''
}

// 选择选项
const selectOption = (option: string) => {
  selectedOption.value = option
}

// 确认选择
const confirmSelection = () => {
  if (selectedOption.value) {
    // 更安全的方式获取数字
    let count = 1;
    switch (selectedOption.value) {
      case '一张牌': count = 1; break;
      case '两张牌': count = 2; break;
      case '三张牌': count = 3; break;
      case '四张牌': count = 4; break;
      case '五张牌': count = 5; break;
      case '六张牌': count = 6; break;
      case '七张牌': count = 7; break;
      default: count = 1;
    }

    // 跳转到卡牌选择页面，通过 URL 参数传递牌数
    uni.navigateTo({
      url: '../card-select/card-select?count=' + count,
      fail: (err) => {
        console.error('跳转失败:', err)
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
    closePopup()
  } else {
    uni.showToast({
      title: '请选择牌数',
      icon: 'none'
    })
  }
}

// 显示随机抽牌弹窗
const showRandomCard = () => {
  showRandomPopup.value = true
  drawRandomCard()
}

// 关闭随机抽牌弹窗
const closeRandomPopup = () => {
  showRandomPopup.value = false
}



// 重新抽牌
const reDrawCard = () => {
  drawRandomCard()
}

// 查看卡片解读
const showCardDetail = () => {
  // 获取当前随机卡片的索引
  const cardIndex = randomCardImage.value.split('/').pop()?.replace('.jpg', '');
  // 跳转到卡片解读页面，通过 URL 参数传递卡片索引和正逆位信息
  uni.navigateTo({
    url: `../card-detail/card-detail?index=${cardIndex}&isReverse=${isReverse.value}`,
    fail: (err) => {
      console.error('跳转失败:', err);
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      });
    }
  });
};

// 跳转到恋人金字塔页面
const navigateToLovePyramid = () => {
  uni.navigateTo({
    url: '../love-pyramid/love-pyramid',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到身心灵页面
const navigateToMindBodySpirit = () => {
  uni.navigateTo({
    url: '../mind-body-spirit/mind-body-spirit',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到事业金字塔页面
const navigateToCareerPyramid = () => {
  uni.navigateTo({
    url: '../career-pyramid/career-pyramid',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到时间之箭页面
const navigateToTimeArrow = () => {
  uni.navigateTo({
    url: '../time-arrow/time-arrow',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到暗恋告白页面
const navigateToSecretCrush = () => {
  uni.navigateTo({
    url: '../secret-crush/secret-crush',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到月运势页面
const navigateToMonthlyFortune = () => {
  uni.navigateTo({
    url: '../monthly-fortune/monthly-fortune',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到桃花运页面
const navigateToLoveFortune = () => {
  uni.navigateTo({
    url: '../love-fortune/love-fortune',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到梦境解读页面
const navigateToDreamReading = () => {
  uni.navigateTo({
    url: '../dream-reading/dream-reading',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到马蹄铁页面
const navigateToHorseshoe = () => {
  uni.navigateTo({
    url: '../horseshoe/horseshoe',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到灵感对应页面
const navigateToInspiration = () => {
  uni.navigateTo({
    url: '/pages/inspiration/inspiration',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到六芒星页面
const navigateToHexagram = () => {
  uni.navigateTo({
    url: '/pages/hexagram/hexagram',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到统治女神页面
const navigateToGoddess = () => {
  uni.navigateTo({
    url: '/pages/goddess/goddess',
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 跳转到心之阴影页面
const navigateToShadow = () => {
  uni.navigateTo({
    url: '../shadow/shadow',
    fail: (err) => {
      console.error('导航到心之阴影页面失败:', err);
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      });
    }
  });
};

// 添加导航映射
const navigationMap: Record<string, () => void> = {
  '恋人金字塔': navigateToLovePyramid,
  '身心灵': navigateToMindBodySpirit,
  '事业金字塔': navigateToCareerPyramid,
  '时间之箭': navigateToTimeArrow,
  '暗恋告白': navigateToSecretCrush,
  '月运势': navigateToMonthlyFortune,
  '桃花运': navigateToLoveFortune,
  '梦境解读': navigateToDreamReading,
  '马蹄铁': navigateToHorseshoe,
  '灵感对应': navigateToInspiration,
  '六芒星': navigateToHexagram,
  '统治女神': navigateToGoddess,
  '心之阴影': navigateToShadow
}

// 通用导航方法
const navigateToLayout = (layoutName: string) => {
  const navigate = navigationMap[layoutName]
  if (navigate) {
    navigate()
  } else {
    console.error('未找到对应的导航方法:', layoutName)
    uni.showToast({
      title: '页面跳转失败',
      icon: 'none'
    })
  }
}


</script>

<style scoped>
.container {
  min-height: 100vh;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.9);
  /* 添加半透明白色遮罩 */
}

.main-title {
  font-size: 36rpx;
  color: #2c3e50;
  /* 改用深灰色 */
  text-shadow: 0 2rpx 4rpx rgba(255, 255, 255, 0.5);
  /* 白色阴影提升对比度 */
}

.skill-item {
  background: #ffffff;
  border: 1rpx solid #e4e6eb;
  /* 添加边框 */
  color: #2c3e50;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  min-width: 320rpx;
  /* 固定宽度 */
  height: 120rpx;
  border-radius: 16rpx;
  font-size: 28rpx;
}


.popup-title {
  color: #1a1a1a;
}

.card-option {
  color: #333;
  font-size: 28rpx;
}

.skill-tree {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2vw;
  padding: 4vw 0;
}

.title-box {
  text-align: center;
  margin-bottom: 4vw;
}

.main-title {
  font-size: 4vw;
  /* 增大字体大小 */
  font-weight: bold;
  color: white;
  /* 调整字体颜色 */
  text-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  /* 添加文字阴影 */
}

.flex-row {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 2vw;
  width: 100%;
}

.skill-item {
  min-width: 40vw;
  /* 调整最小宽度 */
  height: 10vh;
  /* 调整高度 */
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.15);
  /* 调整背景透明度 */
  border: none;
  /* 去掉边框 */
  border-radius: 2vw;
  /* 调整圆角 */
  font-size: 3vw;
  /* 增大字体大小 */
  color: white;
  transition: all 0.3s;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  /* 添加阴影 */
}

.skill-item:active {
  transform: scale(0.95);
  background: rgba(255, 255, 255, 0.25);
}

/* 弹窗样式 */
.popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.popup-content {
  position: absolute;
  top: 50vh;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-radius: 2.4vw 2.4vw 0 0;
  /* 24rpx改为2.4vw */
  padding: 3vw;
  /* 30rpx改为3vw */

}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 3vw;
  /* 30rpx改为3vw */
  border-bottom: 0.1vw solid #eee;
  /* 1rpx改为0.1vw */
}

.popup-title {
  font-size: 3.2vw;
  /* 32rpx改为3.2vw */
  color: #333;
  font-weight: bold;
}

.popup-close,
.popup-confirm {
  font-size: 2.8vw;
  /* 28rpx改为2.8vw */
  color: #666;
  padding: 1vw;
  /* 10rpx改为1vw */
}

.popup-confirm {
  color: #27ba9b;
}

.card-overflow {
  overflow: auto;
  height: 100%;
}

.card-options {
  padding: 3vw 0;
  /* 30rpx改为3vw */
}

.card-option {
  height: 10vh;
  /* 100rpx改为10vh */
  line-height: 10vh;
  /* 按比例调整行高 */
  text-align: center;
  font-size: 3vw;
  /* 30rpx改为3vw */
  color: #333;
  border-bottom: 0.1vw solid #eee;
  /* 1rpx改为0.1vw */
}

.card-option.active {
  color: #27ba9b;
  font-weight: bold;
}

/* 最后一个选项不需要底部边框 */
.card-option:last-child {
  border-bottom: none;
}

/* 随机抽牌弹窗样式 */
.random-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.random-content {
  width: 80vw;
  background: #fff;
  border-radius: 2vw;
  padding: 3vw;
}

.random-card {
  width: 100%;
  height: 50vh;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 3vw 0;
}

.card-image {
  width: 60%;
  height: 100%;
  transition: transform 0.3s;
}

.card-reverse {
  transform: rotate(180deg);
}

.card-info {
  text-align: center;
  margin-bottom: 3vw;
}

.card-position {
  display: inline-block;
  padding: 1vw 3vw;
  background: rgba(39, 186, 155, 0.1);
  color: #27ba9b;
  border-radius: 3vw;
  font-size: 2.8vw;
}

.action-buttons {
  display: flex;
  gap: 2vw;
}

.action-btn {
  flex: 1;
  height: 9vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 1vw;
  font-size: 2.8vw;
  color: #666;
}

.action-btn.primary {
  background: #27ba9b;
  color: #fff;
}

.skill-item-wrapper {
  position: relative;
  min-width: 40vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

.heart-icon {
  position: absolute;
  top: 50%;
  right: 2vw;
  transform: translateY(-50%);
  width: 3vw;
  height: 3vw;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.5);
  font-size: 3vw;
  /* 与文字大小一致 */
  z-index: 1;
  transition: all 0.3s;
}

.heart-icon.active {
  color: #ff4757;
  transform: translateY(-50%) scale(1.1);
}

.category-title {
  width: 100%;
  padding: 20rpx;
  color: white;
  font-size: 32rpx;
  text-align: center;
  margin: 20rpx 0;
}

.favorite-layouts {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 2vw;
  margin-bottom: 20rpx;
}

.card-image {
  width: 60%;
  height: 100%;
  transition: transform 0.5s ease;
  transform-style: preserve-3d;
  backface-visibility: hidden;
}

.card-drawing {
  animation: drawCard 1.5s ease;
}

@keyframes drawCard {
  0% {
    transform: scale(0.3) translateY(-100vh) rotate(180deg);
    opacity: 0;
  }

  50% {
    transform: scale(0.6) translateY(0) rotate(360deg);
    opacity: 0.5;
  }

  100% {
    transform: scale(1) translateY(0) rotate(720deg);
    opacity: 1;
  }
}

.card-reverse {
  transform: rotate(180deg);
}
</style>
